<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="分单状态" prop="workerOrderstatus">
        <el-select v-model="queryParams.workerOrderstatusList" placeholder="请选择-可多选" multiple  clearable>
          <el-option v-for="dict in workerOrderstatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单合同号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入订单合同号,可模糊查询" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码,可模糊查询" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称,可模糊查询" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="openWorkderOrderView"
          v-hasPermi="['order:orderproduct:edit']">执行分单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              show-summary
              border style="width:100%;" ref="multipleTable" :data="orderproductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="handleDisable">
      </el-table-column>
      <el-table-column label="订单合同号" align="center" prop="contractCode" />
      <el-table-column label="客户名称" align="center" prop="customName" />
      <el-table-column label="单据编号" align="center" prop="orderCode" />
      <el-table-column label="订单日期" align="center" prop="orderDate" width="100px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <el-table-column label="规格型号" align="center" prop="productStandard" />
      <el-table-column label="产品单位" align="center" prop="productUnit" width="80px"/>
      <el-table-column label="产品数量" align="center" prop="productNum" width="80px"/>
      <el-table-column label="已分单数量" align="center" prop="workerOrdernum" width="90px"/>
      <el-table-column label="采样数量" align="center" prop="sampleNum" width="90px"/>
      <el-table-column label="分单状态" align="center" prop="workerOrderstatus" width="80px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.workerorder_status" :value="scope.row.workerOrderstatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <!-- 0:待分单,1:已分单,2:部分分单 -->
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.workerOrderstatus != 0"
                     @click="splitInfo(scope.row)">分单详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.workerOrderstatus != 0"
                     @click="splitCancel(scope.row)">取消分单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 分单计算弹出框 -->
    <el-dialog title="批量分单" :visible.sync="open" width="1600px" :close-on-click-modal ="false" append-to-body>
      <el-row :gutter="10" class="mb8">
        <!--<el-col :span="1.5">
          <el-button type="primary" size="mini" @click="calculateSplitWorkOrder"
                     v-hasPermi="['order:orderproduct:edit']">分单计算</el-button>
        </el-col>-->
        <el-col :span="1.5">
          <el-button type="success" size="mini" @click="calculateSplitWorkOrderAndSyncBom"
                     v-hasPermi="['order:orderproduct:edit']">同步BOM=>分单计算</el-button>
        </el-col>
      </el-row>

      <el-divider>待分单数据</el-divider>
      <el-table v-loading="loading"
                show-summary
                border style="width:100%;" :data="selectedList" @selection-change="handleSelectedChangeOfSplit">
<!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="订单合同号" align="center" prop="contractCode" />
        <el-table-column label="客户名称" align="center" prop="customName" />
        <el-table-column label="单据编号" align="center" prop="orderCode" />
        <el-table-column label="订单日期" align="center" prop="orderDate" width="100px">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderDate, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="产品编码" align="center" prop="productCode" />
        <el-table-column label="规格型号" align="center" prop="productStandard" />
        <el-table-column label="产品单位" align="center" prop="productUnit" width="80px"/>
        <el-table-column label="产品数量" align="center" prop="productNum" width="80px"/>
        <el-table-column label="已分单数量" align="center" prop="workerOrdernum" width="90px"/>
        <el-table-column label="可分单数量" align="center" prop="availableWorkerOrdernum" width="140px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.availableWorkerOrdernum" placeholder="可分单数量" clearable @input="workOrderNumChange(scope.row);"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="已采样数量" align="center" prop="sampleNum" width="90px"/>
        <el-table-column label="采样数量" align="center" prop="sampleNumNew" width="160px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.sampleNumNew" placeholder="采样数量" style="width: 150px" :min="0" clearable @input="sampleNumChange(scope.row);"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <!-- 0:待分单,1:已分单,2:部分分单 -->
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="deleteSelectedOfSplit(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-divider>分单详情</el-divider>
      <template v-for="splitItem in splitWorkOrderList">
<!--        <div style="text-align: left; border: #00afff; color: #ec7c7c;">产品信息：{{splitItem.productCode}} {{splitItem.productName}}</div>-->
        <el-tag :type="splitItem.typeTag" size="medium"  effect="light">
          产品信息：{{splitItem.productCode}} {{splitItem.productName}}
        </el-tag>
        <p></p>
        <el-table
          :data="splitItem.bomSubmitVOList"
          style="width: 100%"
          row-key="id"
          border
          lazy
          :row-style="rowStyle"
          :load="load"
          v-loading="splitLoading"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column label="子项物料编码" align="center" prop="bomCode" width="220px"/>
          <el-table-column label="物料名称" align="center" prop="bomName">
          </el-table-column>
          <el-table-column label="单据编号" align="center" prop="orderCode" width="120px"/>
<!--          <el-table-column label="订单数量" align="center" prop="productNum" />-->
          <el-table-column label="分厂名称" align="center" prop="factoryName" />
          <el-table-column label="班组名称" align="center" prop="teamName" width="120px"/>
          <el-table-column label="物料属性" align="center" prop="bomAttribute" width="90px">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.bom_attribute" :value="scope.row.bomAttribute" />
            </template>
          </el-table-column>
          <el-table-column label="分单数量" align="center" prop="workerOrdernum" width="120px">
            <template slot-scope="scope">
              <el-tag type="success">{{scope.row.workerOrdernum+scope.row.sampleNum}} {{scope.row.bomUnit}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="库存" align="center" prop="storeNum" width="90px"/>
          <el-table-column label="计算异常" align="center" prop="failReason" width="120px" show-overflow-tooltip/>
          <el-table-column label="库存情况" align="center" prop="storeStatus" width="70px">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.store_status" :value="scope.row.storeStatus" />
            </template>
          </el-table-column>
          <el-table-column label="是否分单" align="center" class-name="small-padding fixed-width" prop="methodNum" width="120px">
            <template slot-scope="scope">
              <div v-if="scope.row.levelValue != null
                           && scope.row.levelValue == 1
                           && scope.row.storeNum != null
                           && scope.row.storeNum < (scope.row.workerOrdernum+scope.row.sampleNum)">继续分单</div>
              <div v-else>
                <el-select v-if="scope.row.levelValue != null
                           && scope.row.levelValue == 1
                           && scope.row.storeNum != null
                           && scope.row.storeNum >= (scope.row.workerOrdernum+scope.row.sampleNum)" v-model="scope.row.methodNum"
                           placeholder="请选择">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" prop="methodNum" width="100px">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit"
                         v-if="scope.row.levelValue != null && scope.row.levelValue == 1"
                         @click="adjustWorkerOrder(scope.row)" v-hasPermi="['order:orderproduct:edit']">调整分单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-divider></el-divider>
      </template>
      <div v-if="splitWorkOrderList.length == 0" style="text-align: center;">
        暂无无数据，待分单计算
      </div>

      <div slot="footer" class="dialog-footer" style="display: flex;justify-content: center;">
        <!--<el-button type="primary" @click="syncSingleBom" style="display: flex; justify-content: center">同步BOM</el-button>-->
        <el-button type="primary" @click="submitWorkerOrderOfBatch" style="display: flex; justify-content: center" :disabled="isCompleteSplit">提交分单</el-button>
        <el-button type="primary" @click="goToWorkerPlan" style="display: flex; justify-content: center">立即去排产</el-button>
      </div>
    </el-dialog>

    <!-- 分单提交对话框 -->
    <el-dialog :title="title" :visible.sync="workeropen" width="400px" append-to-body>
      <template>
        <div class="ceshi-content">
            <div class="check_item_block">
              分厂：
              <el-select v-model="formad.factoryId" placeholder="请选择分厂" @change="factorychange($event, ix)">
                <el-option v-for="item in factoryList" :key="item.deptId" :label="item.deptName" :value="item.deptId">
                </el-option>
              </el-select>
            </div>
            <p></p>
            <div class="check_item_block">
              班组：
              <el-select v-model="formad.teamId" placeholder="请选择班组">
                <el-option v-for="item in teamList" :key="item.deptId" :label="item.deptName" :value="item.deptId">
                </el-option>
              </el-select>
            </div>
        </div>
      </template>
      <div slot="footer" class="dialog-footer" style="display: flex;justify-content: center;">
        <el-button type="primary" @click="submitAdjust" style="display: flex; justify-content: center">确定</el-button>
      </div>
    </el-dialog>

     <!-- 分单详情信息对话框 -->
     <el-dialog :title="title" :visible.sync="detailopen" width="1000px" :close-on-click-modal ="false" append-to-body>

      <el-table v-loading="loading" :data="workOrderDetailList">
        <el-table-column label="子项物料编码" align="center" prop="bomCode" />
        <el-table-column label="物料名称" align="center" prop="bomName">
        </el-table-column>
        <el-table-column label="订单数量" align="center" prop="productNum">
        </el-table-column>
        <el-table-column label="分单数量" align="center" prop="workerOrdernum" />
        <el-table-column label="采样数量" align="center" prop="sampleNum" />
        <el-table-column label="分厂名称" align="center" prop="factoryName" />
        <el-table-column label="班组名称" align="center" prop="teamName" />
        <el-table-column label="库存情况" align="center" prop="storeStatus" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.store_status" :value="scope.row.storeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="物料属性" align="center" prop="bomAttribute">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.bom_attribute" :value="scope.row.bomAttribute" />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import {
  listSeparateOrderproduct,
  getWorkerOrderproduct,
  listProductbom,updateOrderproduct
} from "@/api/sm/order/orderproduct";
import { listDept, getDept } from "@/api/system/dept";
import {
  batchSubmitWorkerOrderNew,
  batchSubmitWorkerOrder,
  checkProductNumStore,
  splitCancel,
  listWorkorder,
  calculateWorkerOrderList,
  calculateWorkerOrderListOfBatch,
  calculateWorkerOrderListOfBatchAndSyncBom,
  preCalculateWorkerOrder
} from "@/api/sm/order/workorder";
import { addOutbound } from "@/api/sm/order/outbound";
import { listChildren,syncSingleBom } from "@/api/sm/basic/bominfo";
const { v4: uuidv4 } = require('uuid');

export default {
  name: "Orderinfo",
  dicts: ["order_status", "workerorder_status","store_status","bom_attribute"],
  data() {
    return {
      // 遮罩层
      loading: true,
      splitLoading: false,
      // 选中数组
      ids: [],
      selectedList: [],
      splitWorkOrderList: [],
      codes: [],
      // 非多个禁用
      multiple: true,
      // 非多个禁用
      multiple1: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      // 订单信息表格数据
      orderproductList: [],
      bominfoList: [],
      factoryList: [],
      teamList: [],
      workOrderDetailList: [],
      statusOptions: [
        {
          label: "出库",
          value: 2
        },
        {
          label: "继续分单",
          value: 1,
        }
      ],
      workerOrderstatusOptions: [
        {
          label: "待分单",
          value: 0,
        },
        {
          label: "部分分单",
          value: 2,
        },
        {
          label: "已分单",
          value: 1,
        },
      ],
      // 弹出层标题
      title: "调整分厂和班组",
      // 是否显示弹出层
      open: false,
      bomopen: false,
      workeropen: false,
      detailopen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractCode: null,
        productName: null,
        productCode: null,
        orderDate: null,
        // workerOrderstatus: 0,
        workerOrderstatusList: [0,2],
      },
      // 查询参数
      queryParams1: {
        pageNum: 1,
        pageSize: 100,
        productId: null
      },

      productNum2: 0,
      // 表单参数
      form: {
        productNum: null,
        productId: null,
      },
      // 表单参数
      form1: {
        orderIds: null,
        orderPlanList: null,
      },
      productform:{
        id: null,
        orderCode: null,
        productCode: null,
        productStatus: null,
        workerOrderstatus: null
      },
      outform: {
        productType: 1,
        orderCode: null,
        productId: null,
        productCode: null,
        productName: null,
        factoryName: null,
        factoryId: null,
        outNum: null,
      },
      formad : {
        factoryId: null,
        teamId: null,
        id: null,
      },
      splitChange: false,
      // 表单校验
      rules: {
        planStartDate: [
          { required: true, message: "排产截止时间不能为空", trigger: "blur" },
        ],
      },
      curUuid: null,
      // 是否完成分单操作
      isCompleteSplit: false,
    };
  },
  created() {
    this.getList();
    this.getFactoryList();
  },
  methods: {
    handleInput(value) {
      value = value.replace(/[^\d]/g, '');
    },
    //显示分单详情
    splitInfo(row){
      this.title = "分单详情";
      this.loading = true;
      this.queryParams1.productId = row.id;
      listWorkorder(this.queryParams1).then((response) => {
        this.workOrderDetailList = response.rows;
        this.detailopen = true;
        this.loading = false;
      });
    },
    load(tree, treeNode, resolve) {
      console.log(tree);
      let data = {
        "parentBomCode": tree.bomCode,
        "productId": tree.productId,
        "orderCode": tree.orderCode,
        "customName": tree.customName,
        "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildren(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
          resolve(                            //resolve是组件的
              res.data  //根据自己的格式,将查到的子菜单数组填充
          )
      })
    },
    /** 同步bom */
    syncSingleBom(row) {
      this.loading = true;
      syncSingleBom(this.form.productId,this.form.productCode).then((response) => {
        this.$modal.msgSuccess("同步成功");
        this.open = false;
        this.loading = false;
      });
    },
    submitAdjust(){
      this.bominfoList.map((item, index) => {
        if (item.id == this.formad.id){
          let adjustResult = false;
          item.factoryId=this.formad.factoryId;
          item.teamId=this.formad.teamId;
          this.factoryList.map((item1, index) => {
            if (item1.deptId == this.formad.factoryId){
              item.factoryName=item1.deptName;
              adjustResult = true;
            }
           })
          this.teamList.map((item2, index) => {
            if (item2.deptId == this.formad.teamId){
              item.teamName=item2.deptName;
            }
          });
          if (adjustResult) {
            this.workeropen=false;
            this.$modal.msgSuccess("调整成功");
          } else {
            this.$modal.msgError("调整失败，未找到数据");
          }
        }
      });
     },
     /** 调整 */
     adjustWorkerOrder(row) {
        console.log("==============");
        // console.log(row);
        this.title = "调整分厂和班组";
        this.workeropen=true;
        this.formad.id=row.id;
        this.formad.factoryId=row.factoryId;
        this.getTeamList(row.factoryId);
        this.formad.teamId=row.teamId;
    },
    handleDisable(row, index) {

      if (row.workerOrderstatus == '1') {
        return false
      } else {
        return true
      }
    },
    // 根据分厂id返回组数据集
    async childList(id) {
      let temRes = await listDept({ level: 3, delFlag: 0, parentId: id });
      return temRes.data;
    },
    // 分厂下拉回调
    checkFen(eve, index) {
      listDept({ level: 3, delFlag: 0, parentId: eve }).then((res) => {
        // 初始化每一项的"组"列表值
        this.$set(this.bominfoList[index], "childList", res.data);
      });

      this.$set(this.bominfoList[index], "vModel2", "");
    },

    // 初始每一项的数据组
    fn_groupList() {

      this.bominfoList.forEach((item, ix) => {
        // 初始化每一项的分厂id
        this.$set(this.bominfoList[ix], "vModel", item.factoryId);

        // 初始化每一项的"组"值
        this.$set(this.bominfoList[ix], "vModel2", item.teamId);

        // 初始化每一项的"数量"值this.form.productNum
        this.$set(this.bominfoList[ix], "vModel3", item.workerOrdernum);



        listDept({ level: 3, delFlag: 0, parentId: item.factoryId }).then(
          (res) => {
            // 初始化每一项的"组"列表值
            this.$set(this.bominfoList[ix], "childList", res.data);
          }
        );
      });
    },
    // 增加项
    addCheck() {
      this.bominfoList.push({ id: new Date().getTime(), factoryId: "" });
    },

    // 删除选中项
    delCheck(index) {
      this.bominfoList.splice(index, 1);
    },
    factorychange(){
      this.formad.teamId = null;
      this.getTeamList(this.formad.factoryId);
    },
    getFactoryList() {
      listDept({ level: 2, delFlag: 0 }).then((response) => {
        this.factoryList = response.data;
      });
    },
    getTeamList(factoryId) {
      listDept({ level: 3, delFlag: 0, parentId: factoryId }).then(
        (response) => {
          this.teamList = response.data;
        }
      );
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.workerOrderstatuss = '';
      let selectedStatusList = this.queryParams.workerOrderstatusList;
      if (selectedStatusList) {
        for(let i=0;i<selectedStatusList.length;i++) {
          let status = selectedStatusList[i];
          if (i != selectedStatusList.length -1) {
            this.queryParams.workerOrderstatuss += status + ',';
          } else {
            this.queryParams.workerOrderstatuss += status;
          }
        }
      }
      listSeparateOrderproduct(this.queryParams).then((response) => {
        this.orderproductList = response.rows || [];
        for (const item of this.orderproductList) {
          item.availableWorkerOrdernum = item.productNum;
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contractCode: null,
        customName: null,
        orderDate: null,
        orderRemark: null,
        orderCode: null,
        sailDepart: null,
        productCode: null,
        productName: null,
        productStandard: null,
        productNum: null,
        productUnit: null

      };
      this.resetForm("form");
    },
    // 表单重置
    resetout() {
      this.outform = {
        productType: 1,
        orderCode: null,
        productId: null,
        productCode: null,
        productName: null,
        factoryName: null,
        factoryId: null,
        outNum: null,
      };
      this.resetForm("outform");
    },
    // 表单重置
    resetproduct() {
      this.productform = {
        id: null,
        orderCode: null,
        productCode: null,
        productStatus: null,
        workerOrderstatus: null
      };
      this.resetForm("productform");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //指定行颜色
    rowStyle({ row, rowIndex }) {
      // 根据条件返回行样式对象
      if (row.failReason) { // 替换 yourCondition 为你的条件表达式
        return { background: '#ecbbbb !important' }; // 满足条件的行背景色
      }
      return {};
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.selectedList = selection.map((item) => item);
      this.codes = selection.map((item) => item.productCode);
      this.multiple = !selection.length;

      const ids = this.ids || [];
      // if (ids.length > 0) {
      //   preCalculateWorkerOrder(ids).then((response) => {
      //     console.log("分单计算前置校验,处理返回成功, 结果=" + JSON.stringify(response));
      //   }).catch(()=>{
      //     console.log("分单计算前置校验,处理返回失败");
      //   });
      // }
      if (this.selectedList) {
        for (let cur of this.selectedList) {
          // 初始化 1
          cur.sampleNumNew = 1;
        }
      }
    },
    handleSelectedChangeOfSplit(selection) {
      // TODO
    },
    deleteSelectedOfSplit(row){
      for (let i =0;i <this.orderproductList.length;i++) {
        let cur = this.orderproductList[i];
        if (cur.id === row.id) {
          this.$refs.multipleTable.toggleRowSelection(this.orderproductList[i], false);
          break;
        }
      }
      if (this.selectedList.length === 0) {
        this.splitWorkOrderList = [];
        return;
      }
      let index = this.selectedList.indexOf(row);
      if (index !== -1) {
        this.selectedList.splice(index, 1);
      }
      // 计算后的数据，如果存在也要移除
      if (this.splitWorkOrderList.length != 0) {
        let delId = 0;
        for (let i =0;i <this.splitWorkOrderList.length;i++) {
          let cur = this.splitWorkOrderList[i];
          if (cur.productId === row.id) {
            delId = row.id;
            this.splitWorkOrderList.splice(i, 1);
            break;
          }
        }
        for (let i =0;i <this.ids.length;i++) {
          if (this.ids[i] === delId) {
            this.ids.splice(i, 1);
            break;
          }
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange1(selection) {
      this.multiple1 = !selection.length;
    },
    splitCancel(row) {
      this.loading = true;
      const that = this;
      this.$modal.confirm(`确认要取消 \n [${row.orderCode} / ${row.productName}] \n分单订单吗？`).then(function() {
        splitCancel({
          "orderCode": row.orderCode,
          "productId": row.id,
          "productCode": row.productCode
        }).then(response => {
          that.loading = false;
          that.$modal.msgSuccess("取消成功");
          that.getList();
        }).catch(() => {});
      }).then(() => {
      }).catch(() => {
        this.loading = false;
      });
    },
    openWorkderOrderView() {
      this.splitWorkOrderList = [];
      if (this.ids.length === 0) {
        this.$modal.msgError("没有要处理的数据");
        return;
      }
      this.isCompleteSplit = false;
      this.open = true;
    },
    workOrderNumChange(row) {
      row.availableWorkerOrdernum = row.availableWorkerOrdernum.replace(/[^\d]/g,'');
      this.splitChange = true;
    },
    sampleNumChange(row) {
      // row.sampleNumNew = row.sampleNumNew.replace(/[^\d]/g,'');
      this.splitChange = true;
    },
    calculateSplitWorkOrder() {
      this.calculateSplitWorkOrderAsync(true);
    },
    calculateSplitWorkOrderAndSyncBom() {
      this.calculateSplitWorkOrderAsync(false);
    },
    calculateSplitWorkOrderAsync(isAsync) {
      if (this.ids.length === 0 || this.selectedList.length === 0) {
        this.$modal.msgError("没有要处理的数据");
        return;
      }
      const start = Date.now();
      // 验证
      for (let cur of this.selectedList) {
        let productNum = cur.productNum || 0;
        let workerOrdernum = cur.workerOrdernum || 0;
        let availableWorkerOrdernum = cur.availableWorkerOrdernum || 0;
        let sampleNumNew = cur.sampleNumNew || 0;
        if (availableWorkerOrdernum <= 0) {
          this.$modal.msgError(`处理的产品${cur.productCode} ${cur.productName} 数量为
            ${availableWorkerOrdernum}， 不能小于 0，请确认再试`);
          return;
        }
        if (availableWorkerOrdernum > (productNum-workerOrdernum)) {
          this.$modal.msgError(`处理的产品${cur.productCode} ${cur.productName} 数量为
            ${availableWorkerOrdernum} > ${productNum-workerOrdernum} 已经超过可分单数量，请确认再试`);
          return;
        }
        if (sampleNumNew > (productNum-workerOrdernum)) {
          this.$modal.msgError(`处理的采样产品${cur.productCode} ${cur.productName} 数量为
            ${sampleNumNew} > ${productNum-workerOrdernum} 已经超过可分单数量，请确认再试`);
          return;
        }
      }

      const loading = this.$loading({
        lock: true,
        text: '分单计算中，请耐心等待计算结果～感谢',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.splitLoading = true;
      const ids = this.ids; // TODO 之前的参数
      let data = []; // 最新的参数
      for (let cur of this.selectedList) {
        data.push({
          productId: cur.id,
          productNum: cur.productNum,
          workerOrdernum: cur.workerOrdernum || 0,
          availableWorkerOrdernum: cur.availableWorkerOrdernum || 0,
          sampleNum: cur.sampleNumNew || 0
        });
      }

      this.splitWorkOrderList = [];
      if (isAsync) {
        calculateWorkerOrderListOfBatch(data).then((response) => {
          this.splitWorkOrderList = response.data || [];
          this.$modal.msgSuccess(`分单计算操作结束,耗时=${(Date.now()-start)/1000}秒`);
          this.splitLoading = false;
          this.bominfoList = [];
          for (let obj of this.splitWorkOrderList) {
            for (let bom of obj.bomSubmitVOList) {
              this.bominfoList.push(bom);
            }
          }
          loading.close();
          console.log(this.bominfoList);
          this.splitChange = false;
        }).catch(() => {
          loading.close();
          this.splitWorkOrderList = [];
          this.splitLoading = false;
          this.splitChange = false;
        });
      } else {
        calculateWorkerOrderListOfBatchAndSyncBom(data).then((response) => {
          this.splitWorkOrderList = response.data || [];
          this.$modal.msgSuccess(`同步BOM并分单计算操作结束,耗时=${(Date.now()-start)/1000}秒`);
          this.splitLoading = false;
          this.bominfoList = [];
          for (let obj of this.splitWorkOrderList) {
            for (let bom of obj.bomSubmitVOList) {
              this.bominfoList.push(bom);
            }
          }
          loading.close();
          console.log(this.bominfoList);
          this.splitChange = false;
        }).catch(() => {
          loading.close();
          this.splitWorkOrderList = [];
          this.splitLoading = false;
          this.splitChange = false;
        });
      }
    },

    handleWorkerOrder(row) {
      this.loading = true;
      this.reset();

      this.bominfoList=null;
      const id = row.id || this.ids;
      checkProductNumStore(id).then((response) => {
        if(response.data){
          let that=this;
          this.$modal.confirm('库存已经满足订单数量,确认是继续分单,取消是库存直接出货?').then(function() {
            // 继续分单
            getWorkerOrderproduct(id).then((response) => {
              that.open = true;
              that.title = "执行分单";

              that.form = response.data;
              that.productNum2 = response.data.productNum-response.data.workerOrdernum;
              that.form.productId = response.data.id;
            });
          }).then(() => {

          }).catch(() => {
            // 库存出货
            this.resetout();
            this.resetproduct();
            this.outform.productType=1;
            this.outform.orderCode=row.orderCode;
            this.outform.productId=row.id;
            addOutbound(this.outform).then(response => {
              this.productform.id=row.id;
              this.productform.workerOrderstatus=3;
              this.productform.productStatus=1;
              updateOrderproduct(this.productform).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            });
          });
          listProductbom(id).then((response2) => {
              that.bominfoList = response2.data;
               that.loading = false;
            });
        }else{
          // 继续分单
          getWorkerOrderproduct(id).then((response) => {
            this.open = true;
            this.title = "执行分单";
            this.form = response.data;
            this.productNum2 = response.data.productNum-response.data.workerOrdernum;
            this.form.productId = response.data.id;
          });

          // 查询 bom 数据
          listProductbom(id).then((response) => {
              this.bominfoList = response.data;
              this.loading = false;
          });
        }

      }).catch(()=>{
        // 查询 bom 数据
        listProductbom(id).then((response) => {
          this.bominfoList = response.data;
          this.loading = false;
        });
        this.loading = false;
      });

    },

    submitWorkerOrderOfBatch() {
      if (this.splitWorkOrderList.length === 0) {
        this.$modal.msgError("由于没有发起分单计算，没有要提交的数据");
        return;
      }
      if (this.splitChange) {
        this.$modal.msgError("您已经手动改变了分单数量，请先重现进行分单计算再提交～");
        return;
      }
      // if (this.isCompleteSplit) {
      //   this.$modal.msgWarning("您已经完成分单提交，请点击立即去排产按钮～");
      //   return;
      // }
      this.splitLoading = true;
      this.isCompleteSplit = false;
      let paramList = [];
      try {
        for(let i=0;i<this.splitWorkOrderList.length;i++) {
          let workOrder = this.splitWorkOrderList[i];
          // if (!workOrder.workerOrdernum || workOrder.workerOrdernum <= 0) {
          //   this.$modal.msgError(`${workOrder.productCode}已分单的数量存在异常，为${workOrder.workerOrdernum}`);
          //   return;
          // }
          if (!workOrder.availableWorkerOrdernum || workOrder.availableWorkerOrdernum <= 0) {
            this.$modal.msgError(`${workOrder.productCode}分单的数量需要大于 0，你填写的是：${workOrder.workerOrdernum}`);
            return;
          }
          paramList.push({
            orderCode: workOrder.orderCode,
            productId: workOrder.productId,
            productCode: workOrder.productCode,
            productName: workOrder.productName,
            productNum: workOrder.productNum,
            contractCode: workOrder.contractCode,
            // 三个参数是针对这个产品的，暂时没有用到，对于产生半成品工单信息没有使用到
            workerOrdernum: workOrder.workerOrdernum || 0, // 已分单的数量
            availableWorkerOrdernum: workOrder.availableWorkerOrdernum || 0, // 需要分单的数量
            sampleNum: workOrder.sampleNum || 0, // 需要采样的数量
            bomSubmitVOList: workOrder.bomSubmitVOList,
          })
        }
      } catch (e) {
        this.$modal.msgError(e.message);
        return;
      }
      // if (true) {
      //   console.log(paramList);
      //   this.$modal.msgError("批量提交分单,模拟成功");
      //   localStorage.setItem(`split_${uuid}`, JSON.stringify(this.selectedList));
      //   debugger
      //   return;
      // }

      batchSubmitWorkerOrderNew(paramList).then((response) => {
          this.$modal.msgSuccess("批量提交分单成功");
          this.workeropen = false;
          this.splitLoading = false;
          // 批量分单页面,对话框暂时不关闭，需要可以让用户立即去分单页排产
          // this.open = false;
          const uuid = uuidv4();
          this.isCompleteSplit = true;
          this.curUuid = uuid;
          localStorage.setItem(`split_${uuid}`, JSON.stringify(this.splitWorkOrderList));
          this.getList();
        }).catch(()=>{
          this.splitLoading = false;
          this.isCompleteSplit = false;
        });
      },
    goToWorkerPlan() {
      // TODO 页面跳转并拉起排产页面数据
      // const jobId = this.$route.params && this.$route.params.jobId;
      // this.$router.push('/monitor/job-log/index/' + jobId)
      if (!this.isCompleteSplit) {
        this.$modal.msgError("还未完成分单提交，无法去进行排产操作，请先完成分单提交");
        return;
      }
      // const uuid = uuidv4();
      // this.curUuid = uuid;
      // localStorage.setItem(`split_${this.curUuid}`, JSON.stringify(this.splitWorkOrderList));
      console.log("uuid=", this.curUuid);
      this.$router.push(`/plan/order_newplan_pending_index?p=${this.curUuid}`);
    },
  },
}
</script>



<style scoped lang="scss">
.ceshi-content {
  .check_btn {
    display: flex;

    div {
      margin-right: 30px;
    }
  }

  .check_item {
    display: flex;
    margin-top: 30px;
  }
  .choose-row {
    background-color: #ecbbbb !important;
  }
}
</style>

